package com.lwq.imserver.controller;

import com.lwq.imserver.model.system.SysUser;
import com.lwq.imserver.service.LoginService;
import com.lwq.imserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/20 15:26
 */
@RestController
@CrossOrigin("*")
public class LoginController {

    @Autowired
    private LoginService service;
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    @CrossOrigin("*")
    public Object login(@RequestBody SysUser user){
        return this.service.doLogin(user);
    }

    /**
     * 登出
     * @param request
     */
    @PostMapping("/logout")
    @CrossOrigin("*")
    public void logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        service.logout(token);
    }

    /**
     * 注册
     * @param user
     */
    @PostMapping("/register")
    @CrossOrigin("*")
    public void register(@RequestBody SysUser user){
        userService.add(user);
    }

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/user/list")
    @CrossOrigin("*")
    public List<SysUser> userList (@RequestParam(required = false) Boolean isOn,
                                   @RequestParam(required = false) String userId,
                                   @RequestParam(required = false) Boolean isAddFriends){
        if(Objects.isNull(isAddFriends)) isAddFriends = false;
        return userService.userList(isOn, userId, isAddFriends);
    }

    /**
     * 更换头像
     * @param map
     */
    @PutMapping("/changeAvatar")
    @CrossOrigin("*")
    public void changeAvatar(@RequestBody Map<String,Object> map){
        String userId = "";
        String avatar = "";
        if(Objects.nonNull(map.get("userId"))){
            userId = map.get("userId").toString();
        }else{
            throw new RuntimeException("参数异常");
        }
        if(Objects.nonNull(map.get("avatar"))){
            avatar = map.get("avatar").toString();
        }else{
            throw new RuntimeException("参数异常");
        }
        userService.changeAvatar(userId, avatar);
    }
}
